package ciyuan.Player;

import ciyuan.Constants.PlayerDataType;
import ciyuan.DataManager.PlayerDataManager;
import ciyuan.Utils.RandomUtil;
import ciyuan.Utils.SoundEventRegistry;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.ai.attributes.Attributes;
import net.minecraft.entity.monster.MonsterEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import static ciyuan.Constants.ExpLevel.needExp;

@Mod.EventBusSubscriber
public class LevelUpper {

    @SubscribeEvent
    public static void onKilling(LivingDeathEvent event) {
        long expAdded = 100 + RandomUtil.randomInt(-10, 10);
        if (event.getSource().getEntity() instanceof ServerPlayerEntity) {
            ServerPlayerEntity player = (ServerPlayerEntity) event.getSource().getEntity();
            if (event.getEntityLiving() instanceof MonsterEntity) {
                calculateAndUpdateLevel(expAdded, player);
            }
        }
    }

    private static void calculateAndUpdateLevel(long expAdded, ServerPlayerEntity player) {
        long exp = PlayerDataManager.getLong(player, PlayerDataType.EXP);
        int level = PlayerDataManager.getInt(player, PlayerDataType.LEVEL);
        int attributePoints = PlayerDataManager.getInt(player, PlayerDataType.ATTRBUTE_POINTS);
        long maxExp = needExp[level];

        if (exp + expAdded < maxExp) {
            PlayerDataManager.setServerPlayerData(player, PlayerDataType.EXP, exp + expAdded);
        } else {
            player.getLevel().playSound(null, player.getX(), player.getY(), player.getZ(), SoundEventRegistry.upgradeSound.get(), player.getSoundSource(), 1.0F, 1.0F);
            PlayerDataManager.setServerPlayerData(player, PlayerDataType.MAX_MAGIC, 1000 + 200L * level);
            PlayerDataManager.setServerPlayerData(player, PlayerDataType.EXP, exp + expAdded - maxExp);
            PlayerDataManager.setServerPlayerData(player, PlayerDataType.LEVEL, level + 1);
            PlayerDataManager.setServerPlayerData(player, PlayerDataType.ATTRBUTE_POINTS, attributePoints + 1);
            player.getAttribute(Attributes.MAX_HEALTH).setBaseValue(level * 2 + 20);
        }
    }

    @SubscribeEvent
    public static void onPlayerRespawn(PlayerEvent.PlayerRespawnEvent event) {
        if (event.getPlayer() instanceof ClientPlayerEntity) {
            return;
        }
        int level = PlayerDataManager.getInt(event.getPlayer(), PlayerDataType.LEVEL);
        event.getPlayer().getAttribute(Attributes.MAX_HEALTH).setBaseValue(level * 2 + 20);
    }

}
